<?php
namespace cms\modules\frontend\controllers;

use Yii;
use common\component\tool\Member;
use app\models\Content;
use app\models\DynamicDataInfo;
use app\models\MemberStar;
use common\component\tool\Tool;
use common\component\tool\ImageUpload;
use common\component\exception\ErrMap;
use common\component\tool\HttpClient;
use common\models\OperationLog;

class MemberController extends AuthController
{

    /*微信小程序授权 已废弃*/
    public function actionAuthByWechatMiniprogram()
    {
        $code = isset($this->post['code'])?$this->post['code']:'';
        if (empty($code)){
            return Tool::showRes(ErrMap::getError(10005));
        }

        /*上诸山小程序*/
        if($this->appid == 'CMS2020iPM08gWfc24'){
            $appId = 'wxe8699db7b00ec7b2';
            $appSecret = 'd05559f6cf78c8bdede0b91a87cd14c5';
        }

        /*大洋湾小程序*/
        if($this->appid == 'CMS2020mhF08XfM418'){
            $appId = 'wx1426c7452cd69a79';
            $appSecret = '9b3412ea83e97a65eebff6ea4cdcc4ce';
        }

        /*恐龙园小程序*/
        if($this->appid ==  'CMS2020Zoz07KGXe10'){
            $appId = 'wxb5f7fc755cfd3aeb';
            $appSecret = 'a958ad921ff42c7f0fb4cb5cd8eb89b3';
        }

        /*昊视小程序*/
        // $appId = 'wxc8b94c6f52802ebe';
        // $appSecret = '4cdb68672ccd4ecf01c49d3b8f4bc77c';

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appId . "&secret=" . $appSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $httpClient = new HttpClient($url);
        if($res = $httpClient->post() and $res['code'] != 200){
            $returnRes = array(
                'openid' => $res['openid'],
                'sessionid' => session_id(),
            );

            /*入库*/
            $this->post['appid'] = $this->appid;
            $this->post['comid'] = $this->comid;
            $this->post['openid'] = $res['openid'];
            // $this->post['openid'] = '1ot7f6phgcojnrnem7pufgp2fm';
            $this->post['regfrom'] = 3;//来源移动
            $res = $this->member->authByWechatMiniprogram($this->post, $this->app_info_id);
            
            if($res && $res['code'] == 0){
                Yii::$app->session->set('memberInfo', (object)$res['data']);

                return Tool::showRes([0, '授权成功'], $returnRes);
            }else{
                return Tool::showRes(ErrMap::getError(10025));
            }
            
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*注册*/
    public function actionRegister()
    {
        // $member = new Member(Yii::$app->params['ac']);
        // P($this->post);
        /*验证短信正确性*/
        if(($res = $this->checkCode()) !== true){
            return $res;
        }

        $this->post['appid'] = $this->appid;
        $this->post['comid'] = $this->comid;
        if(!Tool::isMobile()){
            $this->post['regfrom'] = 2;//来源PC
        }
        // P($this->post);
        $res = $this->member->register($this->post, $this->app_info_id);
        // P($res);
        if(is_array($res)){
            return json_encode($res);
        }
        return $res;
    }

    /*登录*/
    public function actionLogin()
    {
        $this->post['appid'] = $this->appid;
        $this->post['comid'] = $this->comid;
        $res = $this->member->login($this->post, $this->app_info_id);
        // P($res);
        if($res['code'] == 0){
            // $memberInfo = array(
            //     'memberInfo' => $res,
            // );
            Yii::$app->session->set('memberInfo', (object)$res['data']);
        }
        if(is_array($res)){
            return json_encode($res);
        }
        return $res;
    }

    /*找回密码*/
    public function actionForget()
    {
        // P($this->post);
        /*验证短信正确性*/
        if(($res = $this->checkCode()) !== true){
            return $res;
        }
        
        $this->post['appid'] = $this->appid;
        $this->post['comid'] = $this->comid;
        $res = $this->member->forget($this->post, $this->app_info_id);
        // P($res);
        if(is_array($res)){
            return json_encode($res);
        }
        return $res;
    }

    /*登录之后，获取会员信息*/
    public function actionGetinfo()
    {
        if(isset($this->memberInfo)){
            $member_id = $this->memberInfo->member_id;
            $res = $this->member->getInfo($member_id, $this->app_info_id);
            if(is_array($res)){
                $res['data'] = $res['data'][0];//只要取一个数据,默认返回的是数组
                unset($res['data']['member_id']);
                // P($res);
                return json_encode($res);
            }
        }
        list($errno, $errmsg) = ErrMap::getError(10007);
        return Tool::showRes([$errno, $errmsg]);
    }


    /*上传修改头像*/
    public function actionModheadimg()
    {
        // P($this->post, false);
        // P($this->app_id);
        $imageUpload = new ImageUpload();
        $this->post['catId'] = 0;
        $res =  $imageUpload->upload($this->post, $this->appid, 0, $this->app_id);
        $res = json_decode($res);
        if(isset($res->code) and $res->code == 0){
            $imgurl = $res->info;//上传成功后的图片路径
            $res = $this->actionModInfo($imgurl);
            return $res;
        }
    }

    /*修改会员资料 不带修改密码*/
    public function actionModinfo($imgurl = '')
    {
        if(isset($this->memberInfo)){
            $this->post['appid'] = $this->appid;
            $this->post['member_id'] = $this->memberInfo->member_id;
            if(!empty($imgurl)){
                $this->post['headimgurl'] = $imgurl;
            }
            // P($this->post);
            $res = $this->member->modMemberInfo($this->post, $this->app_info_id);
            if(is_array($res)){
                return json_encode($res);
            }
        }
        list($errno, $errmsg) = ErrMap::getError(10007);
        return Tool::showRes([$errno, $errmsg]);
    }

    /*修改密码*/
    public function actionModpassword()
    {
        // P($this->post);
        if(isset($this->memberInfo)){
            $this->post['appid'] = $this->appid;
            $this->post['comid'] = $this->comid;
            $this->post['member_id'] = $this->memberInfo->member_id;
            // P($this->post);
            $res = $this->member->modMemberPassword($this->post, $this->app_info_id);
            if(is_array($res)){
                return json_encode($res);
            }
        }
        list($errno, $errmsg) = ErrMap::getError(10007);
        return Tool::showRes([$errno, $errmsg]);
    }

    /*验证验证码是否正确*/
    private function checkCode()
    {
        if(isset($this->post['phone']) and isset($this->post['checkcode'])){
            $httpClient = new HttpClient(Yii::$app->params['SMS']['check']);
            $data = [
                'phone' => $this->post['phone'],
                'code' => $this->post['checkcode'],
                'appInfoId' => $this->app_info_id
            ];
            $httpClient->data = $data;
            if($res = $httpClient->post() and $res['code'] != 200){
                // P($res);
                return Tool::showRes(ErrMap::getError(10008));
            }
            return true;
        }
        return Tool::showRes(ErrMap::getError(10008));
    }


    /*安全退出*/
    public function actionLogout()
    {
        Yii::$app->session->set('memberInfo', null);
        if(Yii::$app->session->get('memberInfo') === null){
            return Tool::showRes([0, '成功登出']);
        }else{
            return Tool::showRes(ErrMap::getError(10006));
        }
    }


    /*会员行为 点赞、收藏、评论*/
    public function actionSetStar()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        /*如果有openid, 则可以获取用户信息，实现登录*/
        if(!$this->isLogin() and isset($this->post['openid'])){
            $this->getinfoByOpenid($this->post['openid'], $this->comid);
        }
        if(isset($this->memberInfo)){
            if(isset($this->post['sflag']) and 
                isset($this->post['cflag']) and 
                isset($this->post['contentid'])){
                if($this->post['sflag'] == 3 and 
                (!isset($this->post['comments']) or empty($this->post['comments']))){//说明是评论 comments 不能为空
                    $backInfo = ErrMap::getError(10005, '评论不能为空');//返回信息
                }else{
                    $obj = null;
                    if($this->post['cflag'] == 1){//内容
                        $obj = Content::find()->select('content_id as id')
                                        ->where('content_id = :id', [':id' => $this->post['contentid']])
                                        ->asArray()
                                        ->one();
                    }if($this->post['cflag'] == 2){//动态数据
                        $obj = DynamicDataInfo::find()->select('info_id as id')
                                        ->where('info_id = :id', [':id' => $this->post['contentid']])
                                        ->asArray()
                                        ->one();
                    }
                    // P($obj);
                    if(!is_null($obj)){
                        $contentid = $obj['id'];
                        $transaction = Yii::$app->db->beginTransaction();//事物处理
                        $pass = true;
                        try{
                            /*1、更新行为*/
                            //判断是否存在，如果存在，则删除，说明是取消操作
                            $memberStar = MemberStar::find()
                                                ->where('member_id = :mid and sflag = :sflag and cflag = :cflag and contentid = :contentid and app_id = '.$this->app_id, [':mid' => $this->memberInfo->member_id, ':sflag' => $this->post['sflag'], ':cflag' => $this->post['cflag'], 'contentid' => $contentid])
                                                ->one();
                            // P($memberStar);
                            $has = false;
                            if(!is_null($memberStar) and $this->post['sflag'] != 3){//存在 点赞/收藏 是取消(删除)
                                $has = true;
                                if(!MemberStar::deleteAll('member_id = :mid and sflag = :sflag and cflag = :cflag and contentid = :contentid and app_id = '.$this->app_id, [':mid' => $this->memberInfo->member_id, ':sflag' => $this->post['sflag'], ':cflag' => $this->post['cflag'], 'contentid' => $contentid])){
                                    $pass = false;
                                    $backInfo = ErrMap::getError(20003);//返回信息
                                }
                            }else{//不存在
                                $memberStar = new MemberStar();
                                $this->post['member_id'] = $this->memberInfo->member_id;
                                $this->post['app_id'] = $this->app_id;
                                $this->post['contentid'] = $contentid;
                                $data = array(
                                    'MemberStar' => $this->post
                                );
                                // P($data);
                                if(!$memberStar->addStar($data)){
                                    $pass = false;
                                    $backInfo = ErrMap::getError(20003);//返回信息
                                }
                            }

                            if($pass){
                                $star_num = 0;
                                $praise_num = 0;
                                $reply_num = 0;
                                if($this->post['sflag'] == 1){}
                                switch($this->post['sflag'])
                                {
                                    case 1://收藏
                                        if($has){
                                            $star_num = -1;
                                        }else{
                                            $star_num = 1;
                                        }
                                        break;
                                    case 2://点赞
                                        if($has){
                                            $praise_num = -1;
                                        }else{
                                            $praise_num = 1;
                                        }
                                        break;
                                    case 3://评论
                                        $reply_num = 1;
                                        break;
                                    default:
                                        $star_num = 0;
                                        $praise_num = 0;
                                        $reply_num = 0;
                                }
                                /*2、如果是内容，更新总量*/
                                if($this->post['cflag'] == 1){//内容
                                    Content::updateAllCounters(['star_num' => $star_num, 'praise_num' => $praise_num, 'reply_num' => $reply_num], 'content_id = :contentid', [':contentid' => $contentid]);
                                }

                                /*2、如果是动态数据，更新总量*/
                                if($this->post['cflag'] == 2){//动态数据
                                    DynamicDataInfo::updateAllCounters(['star_num' => $star_num, 'praise_num' => $praise_num, 'reply_num' => $reply_num], 'info_id = :infoid', [':infoid' => $contentid]);
                                }
                                
                            }

                            if($pass){
                                $backInfo = [0, '操作成功'];//返回信息
                                $transaction->commit();
                            }

                        }catch(\Exception $exception){
                            $transaction->rollback();       
                        };
                    }
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        list($errno, $errmsg) = ErrMap::getError(10007);
        return Tool::showRes([$errno, $errmsg]);
    }

    /*我的收藏*/
    public function actionStarList()
    {
        // $this->memberInfo = (object)array(
        //     'member_id' => 24
        // );
        /*如果有openid, 则可以获取用户信息，实现登录*/
        if(!$this->isLogin() and isset($this->get['openid'])){
            $this->getinfoByOpenid($this->get['openid'], $this->comid);
        }
        // P($this->memberInfo);
        if($this->isLogin()){
            if(isset($this->get['cflag']) and in_array($this->get['cflag'], [1, 2])){
                if(isset($this->get['page'])){
                    $currPage = intval($this->get['page']?$this->get['page']:1);
                }else{
                    $currPage = 1;
                }
                if(isset($this->get['pagesize'])){
                    $pageSize = intval($this->get['pagesize']?$this->get['pagesize']:Tool::getPageSize());
                }else{
                    $pageSize = Tool::getPageSize();
                }

                $member_id = $this->memberInfo->member_id;
                $count = MemberStar::find()
                            ->where('member_id = :mid and sflag = 1 and cflag = ' . $this->get['cflag'], [':mid' => $member_id])
                            ->count();
                if($this->get['cflag'] == 1){//内容
                    $memberStar = MemberStar::find()->select(['contentid', 'nickname', 'headimgurl', '{{%member_star}}.add_time'])
                            ->joinWith('content')
                            ->where('member_id = :mid and sflag = 1 and cflag = 1', [':mid' => $member_id])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->orderBy(['{{%member_star}}.add_time' => SORT_DESC])
                            ->asArray()->all();
                    foreach($memberStar as $k => $v){
                        $memberStar[$k]['content_id'] = $v['content']['content_id'];
                        $memberStar[$k]['title'] = $v['content']['title'];
                        $memberStar[$k]['describe'] = $v['content']['describe'];
                        if(!empty($v['content']['preview'])){
                            $memberStar[$k]['preview'] = explode(',', $v['content']['preview']);
                        }else{
                            $memberStar[$k]['preview'] = '';
                        }
                        $memberStar[$k]['star_num'] = $v['content']['star_num'];
                        $memberStar[$k]['praise_num'] = $v['content']['praise_num'];
                        $memberStar[$k]['reply_num'] = $v['content']['reply_num'];
                        unset($memberStar[$k]['contentid']);
                        unset($memberStar[$k]['content']);
                    }
                }else{//动态数据
                    // $dynamicid = intval(isset($this->get['dynamicid'])?$this->get['dynamicid']:0);
                    $memberStar = MemberStar::find()->select(['contentid', 'nickname', 'headimgurl', '{{%member_star}}.add_time'])
                            ->with('dynamicInfo')
                            ->with('dynamic')
                            /*不需要传值了 注意：有了传值，模型必须还要有关联方法，不能删*/
                            // ->with([
                            //     'dynamic' => function ($query) use ($dynamicid) {
                            //         $query->where(['=', 'dynamic_id', $dynamicid]);
                            //     }
                            // ])
                            ->where('member_id = :mid and sflag = 1 and cflag = 2', [':mid' => $member_id])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->orderBy(['{{%member_star}}.add_time' => SORT_DESC])
                            ->asArray()->all();
                    foreach($memberStar as $k => $v){
                        $memberStar[$k]['star_num'] = $v['dynamicInfo']['star_num'];
                        $memberStar[$k]['praise_num'] = $v['dynamicInfo']['praise_num'];
                        $memberStar[$k]['reply_num'] = $v['dynamicInfo']['reply_num'];
                        unset($memberStar[$k]['dynamicInfo']);

                        unset($memberStar[$k]['contentid']);
                        foreach($v['dynamic'] as $k1 => $v1){
                            $memberStar[$k]['info_id'] = $v1['info_id'];
                            $memberStar[$k][$v1['attr_enname']] = $v1['attr_value'];
                        }
                        unset($memberStar[$k]['dynamic']);
                    }
                }
                // P($memberStar);
                $res = array(
                    'list' => $memberStar,
                    'pageInfo' => array(
                        'count' => intval($count),
                        'currPage' => $currPage,
                        'pageSize' => $pageSize,
                    ),
                );
                // P($res);
                return Tool::showRes([0, '获取成功'], $res);
            }
            return Tool::showRes(ErrMap::getError(10005));
        }
        list($errno, $errmsg) = ErrMap::getError(10007);
        return Tool::showRes([$errno, $errmsg]);
    }

}
